package com.hsoft.zhxy.app.demo_03_01.controller;

import com.alibaba.fastjson.JSONObject;
import com.hsoft.zhxy.common.redis.RedisClient;
import com.hsoft.zhxy.common.result.ResultBody;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;


@Api(tags = "demo_03_01 Redis读、写、缓存设计")
@Log4j2
@Validated
@RestController
@RequestMapping(value = "/demo_03_01/demoRedis/", produces = "application/json;charset=UTF-8")
public class Demo006RedisController {

    @Autowired
    RedisClient redisClient;

    /**
     * 写入单字符串类型的值，永不过期。返回值为Null时代表执行失败。
     * @return JSONObject
     */
    @ApiOperation(value = "写入单字符串类型的值，永不过期。返回值为Null时代表执行失败。", notes = "写入单字符串类型的值，永不过期。返回值为Null时代表执行失败。")
    @GetMapping("writeStrInRedis")
    public JSONObject writeStrInRedis(@Valid @NotBlank(message = "Key不可为空") String key, @NotBlank(message = "Value不可为空") String value) {
        String result = redisClient.set(key, value);
        return ResultBody.setData(result);
    }

    /**
     * 写入单字符串类型的值，带过期时间。返回值为Null时代表执行失败。
     * @param key
     * @param value
     * @return JSONObject
     */
    @ApiOperation(value = "写入单字符串类型的值，带过期时间。返回值为Null时代表执行失败。", notes = "写入单字符串类型的值，带过期时间。返回值为Null时代表执行失败。")
    @GetMapping("writeStrInRedisWithTimeOut")
    public JSONObject writeStrInRedisWithTimeOut(@NotNull(message = "Key不可为空") String key,@NotNull(message = "Value不可为空") String value, @NotNull(message = "超时时间不能为空") Long timeout) {
//    public JSONObject writeStrInRedisWithTimeOut( String key, String value, Long timeout) {
        String result = redisClient.set(key, value, timeout);
        if (log.isInfoEnabled()) log.info("key="+key+",value="+value+",timeout="+timeout);
        return ResultBody.setData(result);
    }

    /**
     * 获取单字符串类型的值。返回值为Null时代表执行失败。
     * @param key
     * @return JSONObject
     */
    @ApiOperation(value = "获取单字符串类型的值。返回值为Null时代表执行失败。", notes = "获取单字符串类型的值。返回值为Null时代表执行失败。")
    @GetMapping("getRedisValue")
    public JSONObject getRedisValue(@Valid @NotBlank(message = "Key不可为空") String key) {
        String result = redisClient.get(key);
        return ResultBody.setData(result);
    }

    /**
     * 判断key值是否存在
     * @param key
     * @return JSONObject
     */
    @ApiOperation(value = "判断key值是否存在", notes = "判断key值是否存在")
    @GetMapping("checkRedisKeyExist")
    public JSONObject checkRedisKeyExist(@Valid @NotBlank(message = "Key不可为空") String key) {
        Boolean result = redisClient.hasKey(key);
        return ResultBody.setData(result);
    }
}
